package com.watson.rabbitmq;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import org.apache.commons.lang3.RandomUtils;

/**
 * @program: mytest
 * @description:
 * @author: zhangpeng348@jd.com
 * @date: 2019-07-03 21:08
 **/
public class ConsumerDemo {
    public static void main(String[] args) throws IOException, TimeoutException {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    String queneName = "testQuene";
                    Channel channel = null;
                    Connection connection = RabbitConn.getConnection();
                    channel = connection.createChannel();
                    channel.queueDeclare(queneName, true, false, true, null);
                    channel.queueBind(queneName, ProducerDemo.EXCHANGE_NAME, "");

                    Consumer consumer = new DefaultConsumer(channel) {
                        @Override
                        public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                                   byte[] body) throws IOException {
                            String message = new String(body, "UTF-8");
                            System.out.println(envelope.getExchange() + "," + envelope.getRoutingKey() + "," + message +  ", " + Thread.currentThread());
                            try {
                                int i = RandomUtils.nextInt();
                                int sleep = i % 10000;
                                System.out.println("sleep: " + sleep);
                                Thread.sleep(sleep);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                    };
                    // channel绑定队列，autoAck为true表示一旦收到消息则自动回复确认消息
                    channel.basicConsume(queneName, true, consumer);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        };
        runnable.run();
        runnable.run();
    }

}
